package com.rabot;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;
import java.awt.im.InputContext;

public class CursorChineseTextExample {
    public static void main(String[] args) {
        Robot robot;
        Toolkit toolkit;
        try {
            robot = new Robot();
            toolkit = Toolkit.getDefaultToolkit();
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }
        // 模拟键盘输入中文文本
        String chineseText = "你好，世界！";
        String tmp = getFromClipboard();
        paste(chineseText);
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_V);
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        paste(tmp);
    }

    public static String getFromClipboard() {
        Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
        if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            try {
                return (String) transferable.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                return "";
            }
        }
        return "";
    }

    public static void paste(String txt) {
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(new StringSelection(txt), null);
    }
}
